#include "pdfmanager.h"
#include <windows.h>
#include <regex>

long double PdfManager::fileNumber = 0;
std::_Mutex PdfManager::fileMutex;
string PdfManager::outdir;

PdfManager::PdfManager(void)
{
	outdir = "D:/temp/";
}

PdfManager::~PdfManager(void)
{
}

vector<string> PdfManager::loadPdf(string &pdfFile)
{
	if (fileNumber++ > 30)
		fileNumber = 0;

	vector<string> pdfText;

	if(CreateDirectory(L"D:/temp/", NULL) || ERROR_ALREADY_EXISTS == GetLastError())
		pdfText = pdftotxt(pdfFile, string(outdir.c_str() + std::to_string(fileNumber)));
	
	return pdfText;
}

bool isaPunct(char c)
{
	locale loc;

	return std::ispunct(c, loc);
}

void toLowerCase(string &str)
{
	locale loc;
	str.erase(find_if(str.begin(),str.end(), ptr_fun(isaPunct)),str.end());
	
	for(unsigned i=0;i<str.size();i++)
	{
		str[i] = std::tolower(str[i],loc);
	}

}


vector<string> PdfManager::pdftotxt(const string &pdfFile, const string &textFile)
{	
	const char *srcPdf = pdfFile.c_str();
	const char *toText = textFile.c_str();
	wchar_t cmd[100];
	swprintf(cmd , L"-f 1 -l 1 -layout -enc UTF-8 -q %S %S", srcPdf, toText);

	SHELLEXECUTEINFO ShellInfo;
	
	memset(&ShellInfo, 0, sizeof(ShellInfo));
	ShellInfo.cbSize = sizeof(ShellInfo);
	ShellInfo.hwnd = NULL;
	ShellInfo.lpVerb = L"open";
	ShellInfo.lpFile = L"pdftotext.exe";
	ShellInfo.lpParameters =cmd;
	ShellInfo.nShow = SW_HIDE;
	ShellInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
	ShellExecuteEx(&ShellInfo);
	WaitForSingleObject(ShellInfo.hProcess,INFINITE);

	ifstream ifsm;
	ifsm.open(toText);

	string word;
	vector<string> wordsText;
	
	regex txt_regex("^[A-Za-z]");
	while( ifsm >> word)
	{
		if (regex_search(word,txt_regex))
		{
			toLowerCase(word);
			wordsText.push_back(word);
		}
	}
	ifsm.close();
	return wordsText;
}
